package com.study.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.study.dao.entity.MovieUser;


@RestController
public class MovieUserController {
	
	@Autowired
	RestTemplate restTemplate;
	
	@Autowired
	LoadBalancerClient LoadBalancerClient;

	/*
		http://127.0.0.1:8082/ribbon/1
	 */
	@GetMapping("/ribbon/{id}")
	@HystrixCommand(fallbackMethod = "selectByIdFallback",
		commandProperties = {@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
				             @HystrixProperty(name = "fallback.enabled", value = "true")})
	public MovieUser selectById(@PathVariable("id") int id) {
		//spring.application.name=sunxj-microservice-provider-user
		//vip=virtual ip
		System.out.println("ribbon thread: " + Thread.currentThread().getName());
		MovieUser movieUser = restTemplate.getForObject("http://sunxj-microservice-provider-user/simple/" + id, MovieUser.class);
		return movieUser;
	}


	/*

		http://127.0.0.1:8082/name/1
		测试监控hystrix.stream时用，监控多个接口
	 */
	@GetMapping("/name/{id}")
	@HystrixCommand(fallbackMethod = "selectByIdFallback",
		commandProperties = {@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
				             @HystrixProperty(name = "fallback.enabled", value = "true")})
	public MovieUser selectByName(@PathVariable("id") int id) {
		//spring.application.name=sunxj-microservice-provider-user
		//vip=virtual ip
		MovieUser movieUser = restTemplate.getForObject("http://sunxj-microservice-provider-user/simple/" + id, MovieUser.class);
		return movieUser;
	}

	public MovieUser selectByIdFallback(int id) {
		//spring.application.name=sunxj-microservice-provider-user
		//vip=virtual ip
		MovieUser movieUser = new MovieUser();
		movieUser.setId(0);
		//最后抛出sunxj-microservice-provider-user服务引起的异常，而不是java.lang.ArithmeticException: / by zero
//		int a = 1/0;
		return movieUser;
	}

}
